package totaapplication;

import java.util.Vector;

import tota.middleware.TotaMiddleware;
import tota.tuples.TotaTuple;
import tota.tuples.hop.GradientTuple;
import tuplespace.tuples.Tuple;
import emulator.agent.AbstractAgent;
import emulator.peers.Peer;
import emulator.peers.PeerInterface_ApplicationSide;
import emulator.utils.GenPoint;

public class AppAgent extends AbstractAgent {
	
 private PeerInterface_ApplicationSide peer;
 private TotaMiddleware tota;
 
 
 /*
  * The application agent is created on a peer.
  * It creates a TOTA middleware 
  */
 
 public AppAgent(PeerInterface_ApplicationSide peer) {
  this.peer = peer;
  tota = new TotaMiddleware(peer);
  System.out.println(peer.getAddress() + " starting...");
 }
 
 
 /* 
  * The simulator ciclically invokes this step method with a time step value.
  * The first thing to do is to run the tota middleware (that is also animated in
  * a step-like way).
  */
 
 public void step(int time) {
   tota.step(time);
   
   // since all the nodes run the same agent, it is possible to differentiate their behavior
   // on the basis of their name, or on the basis of the name of the peer in which they are running.
   if(peer.toString().equals("P0")) {
	
	// inject a tuple
	if(time == 10) {
     TotaTuple t = new GradientTuple();
     t.setContent("<content=ciao>"); // this notation is mandatory
     tota.inject(t);
	}
	
	// move. The agent cannot move but can ask its peer to move
	if(time == 50) {
	 Peer p = (Peer) peer.getRealIdentity();
	 p.emu.move(p.toString(), new GenPoint(100, 100));
	}
	
	// read tuples in the local tuple space and in the neighbor tuple spaces.
	if(time == 100) {
	 Tuple allTemplate = new Tuple("<content=*>");
	 Vector local = tota.read(allTemplate);
	 Vector remote = tota.readOneHop(allTemplate);
	}
	
   }
 }
 
 
 
	
	
	
	
	
	
	
	
	/***************************************************************************/
	/*		LOW LEVEL USELESS METHODS 										   */
	/***************************************************************************/
	
	public synchronized void showAgentFrame() {
	}

	public synchronized void hideAgentFrame() {
		peer.shutDown();
	}

	public synchronized Object getRealIdentity() {
		return this;
	}
}